import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import { ElMessageBox, ElMessage } from 'element-plus'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = to.meta.title
  next()
  // console.log(to);

  if (to.path === '/login' || to.path === '/in') {
    // if is logged in, redirect to the home page
    // 检查是否已经连接
    store.dispatch('redis/ping').then((res) => {
      // 已连接
      ElMessageBox.confirm(
        `您已经连到数据库：${store.state.redis.host}:${store.state.redis.port}，可以跳转到管理界面`,
        '已连接',
        {
          confirmButtonText: '跳转',
          cancelButtonText: '重新登录',
          type: 'success',
        }
      ).then(() => {
        router.push({ path: '/home' })
      }).catch(() => {
        
      })
    })
  } else {
    // determine whether the user has obtained his permission roles through getInfo
    store.dispatch('redis/ping').then((res) => {
    }).catch((res) => {
      console.log(res);
      if (res.code == 4014) {
        ElMessageBox.alert('跳转到登录界面', '未连接', {
          confirmButtonText: '确定',
          callback: (action) => {
            router.push({ path: '/login' })
          },
        })
      }
    })
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
